package org.cresource.pay.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import org.cresource.order.domain.AdoptOrder;
import org.cresource.order.service.IAdoptOrderService;
import org.cresource.pay.constants.PayConstants;
import org.cresource.pay.domain.AlipayInfo;
import org.cresource.pay.domain.PayBill;
import org.cresource.pay.service.IAlipayInfoService;
import org.cresource.pay.service.IPayBillService;
import org.cresource.pay.utils.AlipayConfig;
import org.cresource.quartz.service.IQuartzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RestController
public class AlipayController {

    @Autowired
    private IPayBillService payBillService;

    @Autowired
    private IAlipayInfoService alipayInfoService;

    @Autowired
    private IAdoptOrderService adoptOrderService;

//    @Autowired
//    private IQuartzService quartzService;

    @PostMapping("/notify")
    public void notify(HttpServletRequest request){
        System.out.println("支付宝异步回调！");
        //获取支付宝POST过来反馈信息
        try {
            Map<String,String> params = new HashMap<String,String>();
            Map<String,String[]> requestParams = request.getParameterMap();
            for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                valueStr = new String(valueStr);
                params.put(name, valueStr);
            }
            String unionPaySn = params.get("out_trade_no");
            PayBill payBill = payBillService.loadByUnionPaySn(unionPaySn);
            if(payBill != null){
                AlipayInfo info = alipayInfoService.getByShopId(payBill.getShop_id());
                boolean signVerified = AlipaySignature.rsaCheckV1(params,
                        info.getAlipay_public_key(),
                        AlipayConfig.charset,
                        AlipayConfig.sign_type); //调用SDK验证签名

                if(signVerified) {//验证成功
                    //商户订单号
                    String out_trade_no = unionPaySn;

                    //支付宝交易号
                    String trade_no = request.getParameter("trade_no");

                    //交易状态
                    String trade_status = request.getParameter("trade_status");

                    if(trade_status.equals("TRADE_FINISHED")){
                        //用户确认
                    }else if (trade_status.equals("TRADE_SUCCESS")){
                        //1. 改支付单状态
                        payBill.setState(1);
                        payBill.setUpdateTime(new Date());
                        payBillService.update(payBill);
                        String businessType = payBill.getBusinessType();
                        //2.再修改对应（领养）的订单状态  businessType   businessKey 订单
                        if(PayConstants.BUSINESS_TYPE_ADOPT.equals(businessType)){//领养订单
                            Long orderId = payBill.getBusinessKey();
                            AdoptOrder order = adoptOrderService.getById(orderId);
                            order.setState(1);
                            adoptOrderService.update(order);
                        }
//                        //移出 针对当前订单的定时任务
//                        quartzService.removeJob(out_trade_no);
                    }
                }else {//验证失败
                    System.out.println("老宋，不要搞事");

                    //调试用，写文本函数记录程序运行情况是否正常
                    //String sWord = AlipaySignature.getSignCheckContentV1(params);
                    //AlipayConfig.logResult(sWord);
                }
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }





    }

}
